package com.zhny.aiot.led.four.screen.plugin.factory;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhny.aiot.led.four.screen.plugin.config.LedConfig;
import com.zhny.aiot.led.four.screen.plugin.model.LedCommand;

import java.io.UnsupportedEncodingException;

public abstract class AbstractCmdFactory<T> implements ILedCmdFactory  {

    protected final LedConfig config;
    private ILedCmdFactory nextFactory;

    public AbstractCmdFactory(LedConfig config, ILedCmdFactory factory){
        this.config=config;
        nextFactory=factory;
    }

//    protected abstract Object mapperTo(String json);

    protected T acceptJson(String json){
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            return mapper.readValue(json,supportCmdParam());
        } catch (Exception e) {
            return null;
        }
    }

    protected abstract LedCommand onEncode(T param) throws UnsupportedEncodingException;

    protected abstract Class<T> supportCmdParam();

    protected abstract String cmdMethodName();

    protected LedCommand next(String method,String json) throws UnsupportedEncodingException {
        if(nextFactory != null)
            return nextFactory.handler(method,json);
        return null;
    }
}
